package com.itheima.project_cloth.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.project_cloth.pojo.JwtUtils;
import com.itheima.project_cloth.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String string = request.getRequestURL().toString();


        if (string.contains("login")){
            return true;
        }

        String jwt = request.getHeader("token");

        if (jwt==null || jwt.length()==0){
            log.info("jwt不存在,请登录");
            Result error = Result.error("NOT_LOGIN");
            String errorstring = JSONObject.toJSONString(error);
            response.getWriter().write(errorstring);
            return false;
        }

        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.info("jwt不正确,请登录");
            Result error = Result.error("错误");
            String errorstring = JSONObject.toJSONString(error);
            response.getWriter().write(errorstring);
            return false;
        }

        return true;
    }


}
